<?php
require_once('BaseController.php');

/**
 * Sites
 * @author Gedalias
 * @name Categorias
 * @label Categorias
 * @menu 1
 * @menu_secao Conte&uacute;do
 */

class Third_CategoriasController extends BaseController
{
	protected $name = 'categorias';
	protected $configFile = 'third_categorias';
	protected $dao;

	public function init(){
		parent::init();

		//LOAD DAO
		require_once('Categorias.php');
		$this->dao = new Categorias();
	}
	
	/**
	 * Listar categorias
	 * @order 1
	 * @menu 1
	 */
	public function indexAction()
	{
		$grid = new Third_Grid();

		//COLUMNS
		$columns = $this->getColumns();
		if( is_array( $columns ) ){
			foreach( $columns as $key=>$data){
				$grid->addColumn( $data );		
			}
		}
		
		//TIPOS
		$tipos = $this->getEnumItensArray( 'tipo' );
		$this->view->assign('tipos', $tipos );
		
		//ID da categoria em edicao
		$id = $this->getRequest()->getParam('id');
		$this->view->assign('id', $id );
		
		$gridOptions = $this->getGridOptions();
		$this->view->moduleTitle = $gridOptions['caption'];

		$data = $this->getCategoriasData();

		$categoriasSimples = $this->getSimpleCategoriasData( $data );
		
		$this->view->assign('categorias', $data );
		$this->view->assign('categoriasSimples', $categoriasSimples ); 
		
		//LOG OPERATIONS
		$this->log('list');
	}

	/**
	 * Ordenar categorias
	 */
	public function saveTreeAction(){
		
		$saveString = $this->getRequest()->getParam('ids');
		
		try{
			$this->dao->cleanCache();

			$items = explode(",", $saveString );
			$count = count($items);
			for($no=0;$no<$count;$no++){
				$tokens = explode("-",$items[$no]);
			
				$id 			 = $tokens[0];
				$data['posicao'] = $no;
				$data['pai']	 = $tokens[1];
				
				$this->dao->update( $data, "id = '".$id."'");
			}
		
			//LOG OPERATIONS
			$this->log('update', 'SUCCESS', $this->dao->getName(), $id );
			$this->flash('Categorias atualizadas com sucesso.', 'success', '/third/'.$this->name );
		} catch( Zend_Exception $e ){
			//LOG OPERATIONS
			$this->log('update', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );
			$this->flash('Erro ao atualizada categoria .', 'error', '/third/'.$this->name );
		}

		$this->disableViewRender();
		$this->disableLayout();
	}
	/**
	 * Editar categoria
	 */
	public function editAction( ){
		$this->view->assign('moduleTitle', $this->configs->moduleTitle );

		$id = $this->getRequest()->getParam('id');
		$data = array();

			$form = $this->getFormProfile();
			$form->setAction( '/third/'.$this->name.'/edit/id/'.$id );

			if( $this->getRequest()->isPost() ){

				$data = $this->getRequest()->getPost();

				//VALIDATE FORM
				if( $form->isValid( $data ) ){

					$saveData = array(
						'permalink'=>Third_Funcs::generatePermalink($data['permalink']),
						'titulo'=>$data['titulo'],
						'descricao'=>$data['descricao'],
						'status'=>$data['status'],
						'pai'=>$data['pai'],
						'tipo'=>$data['tipo']
					);

					try{
						
						$idSave = $this->db->quote( $id );
						$where = ('id = '.$idSave );
						$objetoId = $this->dao->update( $saveData, $where );
						
						$this->dao->cleanCache();

						//LOG OPERATIONS
						$this->log('update', 'SUCCESS', $this->dao->getName(), $id );
						$this->flash('Categoria atualizada com sucesso.', 'success', '/third/'.$this->name."/index/id/".$id );

						echo true;
					} catch( Zend_Exception $e ){
						//LOG OPERATIONS
						$this->log('update', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );
						$this->flash('Erro ao atualizada categoria .', 'error', '/third/'.$this->name."/index/id/".$id );

						echo false;
					}
				}else{
					$this->view->assign('formErro','Por favor, verifique os erros informados.');
					$form->populate( $data );
				}
			}

		//RETORNA CATEGORIA DO BANCO DE DADOS
		if( $id ){
			$categoria = $this->dao->getById( $id );
			
		}
		
		// CATEGORIAS
		if( $categoria ){
			$this->view->assign('categoria', $categoria );
			$form->populate( $categoria );
		}
		
		$this->view->assign('form',$form );
		
		//LOG OPERATIONS
		$this->log('form','',$this->dao->getName(), $id );

		if( $this->getRequest()->isXmlHttpRequest()){
			$conteudo = utf8_encode( $this->view->render('categorias/edit.phtml') );
			echo ($conteudo);
			
			$this->disableViewRender();
			$this->disableLayout();
		}
	}
	
	/**
	 * Remover categorias
	 */
	public function deleteAction( ){
		$this->view->assign('moduleTitle',$this->configs->moduleTitle );

		$id = $this->getRequest()->getParam('id');
		$confirm = $this->getRequest()->getParam('confirm');

		if( $confirm ){
			$data = $this->getRequest()->getPost();

			//VALIDATE FORM
				$saveData = array(
					'status'=>'2',
					'removido_em' => Third_Funcs::getDate('now','datetime')
				);

				try{
					//Verifica se o usuario tem permissao para cadatrar usuario com o nivel informado
					if( !$this->isAdmin() )
						$whereSiteId = " AND sites_id = ".$this->_logged->sites_id ;

					$idSave = $this->db->quote( $id );
					$where = ('id = '.$idSave.$whereSiteId );
					$objetoId = $this->dao->update( $saveData, $where );

					$this->dao->cleanCache();
					
					//LOG OPERATIONS
					$this->log('delete', 'SUCCESS', $this->dao->getName(), $id );

					$this->flash('Categoria removida com sucesso.', 'success', '/third/'.$this->name );

				} catch( Zend_Exception $e ){
					//LOG OPERATIONS
					$this->log('delete', 'CRITICAL_DB_DELETE_ERROR', $this->dao->getName(), $id );

					$this->flash('Erro ao excluir a categoria. Tente novamente.', 'error', '/third/'.$this->name );
				}
		}

		//RETORNA USUARIO DO BANCO DE DADOS
		$categoria = $this->dao->getById( $id );

		if( $categoria ){
			$this->view->assign('categoria', $categoria );
		}

		//LOG OPERATIONS
		$this->log('delete_call', '', $this->dao->getName(), $id );
	}

	/**
	 * Bloquear/Liberar categoria
	 */
	public function unlockAction( ){
		$this->view->assign('moduleTitle',$this->configs->moduleTitle );

		$id = $this->getRequest()->getParam('id');
		//RETORNA USUARIO DO BANCO DE DADOS
		$site = $this->dao->getById( $id );


		if( $site ){
			$this->view->assign('site', $site );
				
				if( $site['status'] == "1"){
					$status = 0;
				} else {
					$status = 1;
				}
			
				//VALIDATE FORM
				$saveData = array(
					'status'=>$status
				);

				try{
					//Verifica se o usuario tem permissao para cadatrar usuario com o nivel informado
					if( !$this->isAdmin() )
						$whereSiteId = " AND sites_id = ".$this->_logged->sites_id ;

					$idSave = $this->db->quote( $id );
					$where = ('id = '.$idSave.$whereSiteId );

					$objetoId = $this->dao->update( $saveData, $where );

					$this->dao->cleanCache();
					
					//LOG OPERATIONS
					$this->log('update', 'SUCCESS', $this->dao->getName(), $id );

					$this->flash('Opera&ccedil;&atilde;o realizada com sucesso.', 'success', '/third/'.$this->name."/index/id/".$id );

				} catch( Zend_Exception $e ){
					//LOG OPERATIONS
					$this->log('update', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName(), $id );

					$this->flash('N&atilde;o foi poss&iacute;vel realizar a opera&ccedil;&atilde;o. Tente novamente', 'error', '/third/'.$this->name );
				}
		}

		//LOG OPERATIONS
		$this->log('update', '', $this->dao->getName(), $id );
		
		$this->flash('Categoria inexistente. Tente novamente', 'error', '/third/'.$this->name );
	}

	/**
	 * Adiciona categoria
	 * @menu 1
	 */
	public function addAction( ){
		$this->view->assign('moduleTitle',$this->configs->moduleTitle );

		$form = $this->getFormProfile();
		$form->setAction( '/third/'.$this->name.'/add' );
		$form->removeElement('id');

		if( $this->getRequest()->isPost() ){
			
			$data = $this->getRequest()->getPost();
			$saveData = array(
				'titulo'=>$data['titulo'],
				'pai'=>$data['pai'],
				'sites_id'=>$this->_site['id'],
				'permalink'=>Third_Funcs::generatePermalink( $data['titulo'] ),
				'status'=>0,
				'tipo'=>$data['tipo'],
				'criado_em' => Third_Funcs::getDate('now','datetime')
			);

			//VALIDATE FORM
			if( $form->isValid( $saveData ) ){
				
				try{
					$objetoId = $this->dao->insert( $saveData );

					$this->dao->cleanCache();
					
					//LOG OPERATIONS
					$this->log('insert', 'SUCCESS', $this->dao->getName(), $objetoId );

					$this->flash('Categoria cadastrado com sucesso.', 'success', '/third/'.$this->name.'/index/id/'.$objetoId );

				} catch( Zend_Exception $e ){
					//LOG OPERATIONS
					$this->log('insert', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );

					$this->flash('Erro ao cadastrar a categoria. Tente novamente.', 'error', '/third/'.$this->name );
				}
			}else{
				
				$this->view->assign('formErro','Por favor, verifique os erros informados.');
				$form->populate( $data );
			}

					
		}
		
				
		Zend_Debug::dump( $form->getErrors() ) ;
		exit;
			
		//LOG OPERATIONS
		$this->log('insert', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );
		$this->flash('Erro ao cadastrar a categoria. Tente novamente.', 'error', '/third/'.$this->name );
		
		$this->disableViewRender();
	}

	public function getCategoryDataBasic( $id ){
		
		$select = $this->dao->getSelectObject();
		$this->dao->setSelectObject( $select->where(' id != ?', $id ) );

		$data = $this->dao->getAllBySite();
		$cats = array();
		foreach( $data as $d ){
			$cats[$d['id']] = $d['titulo'];
		}
		$this->dao->unsetSelectObject();
		return ( $cats );
	}
	
	/**
	 * Pega profile do formularios de acesso
	 * @return Third_Form
	 */
	public function getFormProfile(){
	    //FORMULARIO DE LOGIN
		$formLogin = null;

		$formConfig = $this->configs->form;

		if( $formConfig ){
			$form = new Third_Form( $formConfig );
			$form->getElement('tipo')->setMultiOptions( $this->getEnumItensArray('tipo') );
			
			$id = $this->getRequest()->getParam('id');
			$form->getElement('pai')->setMultiOptions( array(0=>'Nenhum') );

			$form->getElement('pai')->addMultiOptions( $this->getSimpleCategoriasData(NULL, $id ) );
		} 

		return $form;
	}
	
	/**
	 * Retorna categorias
	 * @return $paginator
	 */
	public function getCategorias(){
		$this->dao->setPage( $this->getRequest()->getParam('page', 0 ) );
		
		$search = $this->getRequest()->getParam('search'); 
		$pagesize = $this->getRequest()->getParam('pagesize');
		$index  = $this->getRequest()->getParam('sidx'); 
		$order  = $this->getRequest()->getParam('sord'); 

		//INDEX
		$select = $this->dao->getSelectObject();


		//QUANTIDADE DE REGISTROS
		if( $pagesize ){ 
			$this->dao->setQuantidadePaginacao( $pagesize );
			$this->view->assign('pagesize', $pagesize );
		}

		//BUSCA
		if( $search ){
			$select->where('nome LIKE "%'.$search.'%"');	
			$this->view->assign('search', $search );
		}

		//EXECUTA
		$this->dao->setSelectObject( $select );
		

		return $this->dao->getCategoriasTree( array('all'=>true) );
	}
	
	public function getCategoriasData(){
		$categoriasList = $this->getCategorias();

		return $categoriasList;
	}
	
	public function getSimpleCategoriasData( $categorias = NULL, $id = NULL ){

		if( $id ){
			$select = $this->dao->getSelectObject();
			$this->dao->setSelectObject( $select->where(' id != ?', $id ) );
		}

		if(!$categorias){
			$categorias = $this->getCategoriasData();
		}
		$this->dao->unsetSelectObject();

		$array = array();
		foreach( $categorias as $c ){
			$array[ $c['id'] ] = $c['titulo'];
		}
		return $array;
	}

	public function getGridEditOptions( $id = '' ){

			$cont ="<ul id='icons' >";
			$cont .= "<li class='ui-state-default ui-corner-all'><a href='/third/".$this->name."/edit/id/".$id."' title='Editar' class='ui-icon tooltip edit ui-icon-pencil'>Editar</span></a></li>"; 
			$cont .= "<li class='ui-state-default ui-corner-all'><a href='/third/".$this->name."/view/id/".$id."' title='Visualizar' class='ui-icon tooltip view ui-icon-zoomin' >Visualizar</span></a></li>"; 
			$cont .= "<li class='ui-state-default ui-corner-all'><a href='/third/".$this->name."/delete/id/".$id."' title='Excluir' class='ui-icon tooltip delete ui-icon-minus' >Excluir</a></span></li>"; 
			$cont .="</ul>";

			return $cont;		
	}

	/**
	 * Lista categorias em formato Json
	 */
	public function listJsonAction(){
		$data = $this->getUsuariosData();

		echo json_encode( $data );

		//DISABLE VIEW
		$this->disableLayout();
		$this->disableViewRender();
		
		//LOG OPERAIONS
		$this->log('list');
	}
}